package com.alisonyu.spider.Scheduler;

import com.alisonyu.spider.Downloader.Request;
import com.alisonyu.spider.cluster.ClusterServerVerticle;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.json.JsonObject;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ClusterClientScheduler implements Schedule {

    private EventBus eb;
    private JsonObject emptyJson = new JsonObject();

    public ClusterClientScheduler(EventBus eventBus){
        this.eb = eventBus;
    }

    @Override
    public Request getRequest() {
        CompletableFuture<Request> future = new CompletableFuture<>();
        eb.<JsonObject>send("request.get",emptyJson,rs->{
             if (rs.succeeded()){
                 JsonObject json = rs.result().body();
                 int status = json.getInteger("status");
                 if (status == 0){
                     future.complete(null);
                 }else{
                     future.complete(Request.toRequest(json.getJsonObject("request")));
                 }
             }else{
                 rs.cause().printStackTrace();
                 future.complete(null);
             }
        });
        try {
            return future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void putUrl(String url) {
        Request request = new Request(url);
        putRequest(request);
    }

    @Override
    public void putRequest(Request request) {
        JsonObject json = request.toJsonObject();
        eb.<JsonObject>send("request.put",json);
    }
}
